layui.config({
    base: "js/"
}).use(['form', 'layer', 'jquery', 'laypage','laydate'], function () {
    var form = layui.form(),
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        laypage = layui.laypage,
        $ = layui.jquery;

    //加载页面数据
    var newsData = '';

    var jsonPar={};
    jsonPar.index=1;
    jsonPar.num=13;
    ajaxget("system/userawardlist", jsonPar, function (data) {
        var newArray = [];

        //单击首页“待审核文章”加载的信息
        if ($(".top_tab li.layui-this cite", parent.document).text() == "待审核文章") {

            if (window.sessionStorage.getItem("addNews")) {
                var addNews = window.sessionStorage.getItem("addNews");
                newsData = JSON.parse(addNews).concat(data.data);
            } else {
                newsData = data.data;
            }

            for (var i = 0; i < newsData.length; i++) {
                // if(newsData[i].newsStatus == "待审核"){
                newArray.push(newsData[i]);
                // }
            }
            newsData = newArray;
            newsList(newsData);
        } else {    //正常加载信息

            newsData = data.data;
            if (window.sessionStorage.getItem("addNews")) {
                var addNews = window.sessionStorage.getItem("addNews");
                newsData = JSON.parse(addNews).concat(newsData);
            }
            //执行加载数据的方法
            newsList(newsData,data.maxPage);
        }
    })


    //查询
    $(".search_btn").click(function () {


        var username=document.getElementById("username").value

        var index = layer.msg('查询中，请稍候', {icon: 16, time: false, shade: 0.8});
        var json={};
        json.name=username;
        json.num=13;
        json.index=1;
        setTimeout(function () {
            ajaxget("system/userawardlist",json,function (data) {

                if (data.code != 200) {
                    layer.msg(data.msg, {icon: 0})
                    return null;
                }else
                {
                    layer.msg("查询成功", {icon: 1})
                    $("#tbody").html("");//清除原来的数据
                }
                if (window.sessionStorage.getItem("addNews")) {
                    var addNews = window.sessionStorage.getItem("addNews");
                    newsData = JSON.parse(addNews).concat(data.data);
                } else {
                    newsData = data.data;
                }
                var maxPage=newsData.maxPage;

                newsList(newsData,maxPage);
            })

            layer.close(index);
        }, 1000);






    })

    //添加文章
    $(".newsAdd_btn").click(function () {
        layer.open({
            type: 2,
            title: '添加奖品',
            shadeClose: true,
            shade: 0.8,
            area: ['50%', '80%'],
            content: 'page/count/serviceAdd.html'//iframe的url
        });
    })

    //推荐文章
    $(".recommend").click(function () {
        var $checkbox = $(".news_list").find('tbody input[type="checkbox"]:not([name="show"])');
        if ($checkbox.is(":checked")) {
            var index = layer.msg('推荐中，请稍候', {icon: 16, time: false, shade: 0.8});
            setTimeout(function () {
                layer.close(index);
                layer.msg("推荐成功");
            }, 2000);
        } else {
            layer.msg("请选择需要推荐的文章");
        }
    })

    //审核文章
    $(".audit_btn").click(function () {
        var $checkbox = $('.news_list tbody input[type="checkbox"][name="checked"]');
        var $checked = $('.news_list tbody input[type="checkbox"][name="checked"]:checked');
        if ($checkbox.is(":checked")) {
            var index = layer.msg('审核中，请稍候', {icon: 16, time: false, shade: 0.8});
            setTimeout(function () {
                for (var j = 0; j < $checked.length; j++) {
                    for (var i = 0; i < newsData.length; i++) {
                        if (newsData[i].newsId == $checked.eq(j).parents("tr").find(".news_del").attr("data-id")) {
                            //修改列表中的文字
                            $checked.eq(j).parents("tr").find("td:eq(3)").text("审核通过").removeAttr("style");
                            //将选中状态删除
                            $checked.eq(j).parents("tr").find('input[type="checkbox"][name="checked"]').prop("checked", false);
                            form.render();
                        }
                    }
                }
                layer.close(index);
                layer.msg("审核成功");
            }, 2000);
        } else {
            layer.msg("请选择需要审核的文章");
        }
    })

    //批量删除
    $(".batchDel").click(function () {
        var $checkbox = $('.news_list tbody input[type="checkbox"][name="checked"]');
        var $checked = $('.news_list tbody input[type="checkbox"][name="checked"]:checked');
        if ($checkbox.is(":checked")) {
            layer.confirm('确定删除选中的信息？', {icon: 3, title: '提示信息'}, function (index) {
                var index = layer.msg('删除中，请稍候', {icon: 16, time: false, shade: 0.8});
                setTimeout(function () {
                    //删除数据
                    for (var j = 0; j < $checked.length; j++) {
                        for (var i = 0; i < newsData.length; i++) {
                            if (newsData[i].newsId == $checked.eq(j).parents("tr").find(".news_del").attr("data-id")) {
                                newsData.splice(i, 1);
                                newsList(newsData);
                            }
                        }
                    }
                    $('.news_list thead input[type="checkbox"]').prop("checked", false);
                    form.render();
                    layer.close(index);
                    layer.msg("删除成功");
                }, 2000);
            })
        } else {
            layer.msg("请选择需要删除的文章");
        }
    })

    //全选
    form.on('checkbox(allChoose)', function (data) {
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
        child.each(function (index, item) {
            item.checked = data.elem.checked;
        });
        form.render('checkbox');
    });

    //通过判断文章是否全部选中来确定全选按钮是否选中
    form.on("checkbox(choose)", function (data) {
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
        var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
        if (childChecked.length == child.length) {
            $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
        } else {
            $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
        }
        form.render('checkbox');
    })

    //是否展示
    form.on('switch(isShow)', function (data) {
        var userid = data.value

        try {
            ajaxpost("admin/usereditstatus", {usersid: userid}, function (data) {
                var index = layer.msg('修改中，请稍候', {icon: 16, time: false, shade: 0.8});
                if (data.val == 200) {
                    setTimeout(function () {
                        layer.close(index);
                        layer.msg("状态修改成功！");
                    }, 1000);
                }
                else {
                    setTimeout(function () {
                        layer.close(index);
                        layer.msg("展示状态修改失败！");
                    }, 1000);
                }
            })
        }catch (e)
        {
            setTimeout(function () {
                layer.close(index);
                layer.msg("展示状态修改失败！");
            }, 1000);
        }
    })

    //操作
    $("body").on("click", ".news_edit", function (e) {  //编辑

        var getid = e.target.attributes.id.value
        layer.open({
            type: 2,
            title: '商品修改',
            shadeClose: true,
            shade: 0.8,
            area: ['40%', '80%'],
            content: 'page/task/taskedit.html?id=' + getid  //iframe的url
        });
        // layer.alert('您点击了文章编辑按钮，由于是纯静态页面，所以暂时不存在编辑内容，后期会添加，敬请谅解。。。', {icon: 6, title: '文章编辑'});
    })

    $("body").on("click", ".news_collect", function () {  //收藏.
        if ($(this).text().indexOf("已收藏") > 0) {
            layer.msg("取消收藏成功！");
            $(this).html("<i class='layui-icon'>&#xe600;</i> 收藏");
        } else {
            layer.msg("收藏成功！");
            $(this).html("<i class='iconfont icon-star'></i> 已收藏");
        }
    })

    $("body").on("click", ".news_del"||".icon-edit", function (e) {  //删除
        layer.confirm('确定删除此信息？', {icon: 3, title: '提示信息'}, function (index) {

            var id = e.target.attributes.id.value;
            ajaxget("system/userawardel",{id:id},function (data) {

                if(data.code!=200) {
                    layer.msg("姿势不对，请重新操作！")
                }
                layer.msg(data.msg)
            })
            layer.close(index);
            setTimeout("parent.location.reload()",1500);

        });
    })

    function newsList(that,maxPage) {
        //渲染数据
        function renderDate(data, curr) {
            var dataHtml = '';
            if (!that) {
                currData = newsData.concat().splice(curr * nums - nums, nums);
            } else {
                currData = that.concat().splice(curr * nums - nums, nums);
            }

            if (that.length != 0) {
                for (var i = 0; i < that.length; i++) {
                    dataHtml += '<tr>'
                        + '<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
                        + '<td align="left" style="text-align: center">' + that[i].id + '</td>'
                        + '<td align="left" style="text-align: center">' + decodeURI(that[i].name) + '</td>'
                        + '<td align="left" style="text-align: center"> '+ that[i].awardname + '</td>'
                        + '<td align="left" style="text-align: center"> '+ that[i].number + '件</td>'
                    dataHtml += '<td>'
                    //     + '<a class="layui-btn layui-btn-mini news_edit" id=' + that[i].id + '><i class="iconfont icon-edit" id=' + that[i].id + ' ></i> 编辑</a>'
                    //     + '<a class="layui-btn layui-btn-normal layui-btn-mini news_collect" usersid=' + that[i].id + '><i class="layui-icon">&#xe600;</i> 收藏</a>'
                        + '<a class="layui-btn layui-btn-danger layui-btn-mini news_del" id=' + that[i].id + '><i class="layui-icon">&#xe640;</i> 删除</a>'
                        + '</td>'
                        // + '</tr>';
                }
            } else {
                dataHtml = '<tr><td colspan="9">暂无数据</td></tr>';
            }
            return dataHtml;
        }

        //分页
        var nums = 13; //每页出现的数据量
        if (that) {
            newsData = that;
        }

        // laypage({
        //     cont: "page",
        //     pages: Math.ceil(newsData.length / nums),
        //     jump: function(obj) {
        //         $(".news_content").html(renderDate(newsData, obj.curr));
        //         $('.news_list thead input[type="checkbox"]').prop("checked", false);
        //         form.render();
        //     }
        // })

        laypage({
            cont: "page",
            count:maxPage,
            curr:jsonPar.index,
            pages: Math.ceil(maxPage / nums),

            jump: function (obj,first) {

                jsonPar.index=obj.curr; //分页下标
                $(".news_content").html(renderDate(that, obj.curr));
                $('.news_list thead input[type="checkbox"]').prop("checked", false);
                form.render();
                if(!first){  //判断是否第一次分页 回调渲染

                    ajaxget("system/userawardlist",jsonPar,function (data) {
                        // console.log("开始进行分页渲染")
                        if(data.code!=200) {
                            layer.msg("数据跑到银河系了...",{icon: 0})
                        }else {

                            newsList(data.data, data.maxPage);
                        }
                    })
                }



            }
        })
    }
})


function formatDateTime(inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
};